#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@Time         :  2020/4/2 8:55
@Author       :  geqh
@file         :  compile.py
@introduction :  
"""
from utils.log import *
import shutil
import compileall
import sys


def proc_target(file_dir_parent):
    file_list = os.listdir(file_dir_parent)
    for file in file_list:
        file_path = os.path.join(file_dir_parent, file)
        if os.path.isdir(file_path):
            if file == "__pycache__":
                pyc_file_list = os.listdir(file_path)
                for pyc_file in pyc_file_list:
                    if pyc_file.endswith(".pyc"):
                        pyc_file_path = os.path.join(file_path, pyc_file)
                        pyc_file_replace = pyc_file.replace(version_suffix, "")
                        pyc_file_path_replace = os.path.join(file_dir_parent, pyc_file_replace)
                        # logger.info(pyc_file_path_replace)
                        shutil.copy(pyc_file_path, pyc_file_path_replace)
                logger.info("shutil.rmtree--------------"+file_path)
                shutil.rmtree(file_path)
            else:
                proc_target(file_path)
        else:
            if file.endswith(".py"):
                logger.info("os.remove--------" + file_path)
                os.remove(file_path)


logger.info("-----------begin to compile-----------")
proj_name = os.path.basename(proj_path)
target_dir = os.path.join(proj_path, "target")
logger.info(target_dir)
if os.path.exists(target_dir):
    logger.info(target_dir + " exists, shutil rmtree")
    shutil.rmtree(target_dir)

proj_compile_dir = os.path.join(target_dir, proj_name)

logger.info("copy proj_path to target_dir")
ignore = shutil.ignore_patterns("compile", "target", "venv", ".gitignore", ".idea", "logs", ".git")
shutil.copytree(proj_path, proj_compile_dir, symlinks=False, ignore=ignore)

logger.info("compile_dir:" + target_dir)
compileall.compile_dir(target_dir)

version = str(sys.version_info.major) + str(sys.version_info.minor)
version_suffix = ".cpython-"+version
python_suffix = ".py"
print(version_suffix)

proc_target(target_dir)

logger.info("-----------end to compile-----------")